//
//  TYZIndicateView.m
//  aaaaaa
//
//  Created by 李贤立 on 16/10/19.
//  Copyright © 2016年 Capfer. All rights reserved.
//

#import "TYZIndicateView.h"

#define TYZIndicateViewButtonTags  TAG_LIBRARY_IndicateView_Buttons
#define TYZIndicateViewImageTags   TAG_LIBRARY_IndicateView_Images
#define TYZIndicateViewImageName   @"small_daosanjiao"

@interface TYZIndicateView ()<UIScrollViewDelegate>
/**
 *  scrollView
 */
@property (nonatomic, strong) UIScrollView *scrollView;
/**
 *  数据源
 */
@property (nonatomic, strong) NSArray<NSString *> *nameArray;
/**
 *  装有scrollView中所有按钮的数组
 */
@property(nonatomic, strong) NSArray<UIButton *> *buttonArray;
/**
 *  该指示器的高
 */
@property(nonatomic, assign) CGFloat height;
@end
@implementation TYZIndicateView
/**
 *  创建指示器
 *
 *  @param nameArray 传入的数据源
 *  @param height    该指示器的高
 */
- (instancetype)initWithNameArray:(NSArray<NSString *> *)nameArray height:(CGFloat)height {
    if (self = [super init]) {
        self.backgroundColor = BackgroundColor;
        self.height = height;
        self.nameArray = nameArray;
        [self setupUI];
    }
    return self;
}
#pragma mark - 设置UI
- (void)setupUI {
    [self addSubview:self.scrollView];
    [self addLine];
    self.scrollView.clipsToBounds = NO;
    self.scrollView.pagingEnabled = YES;
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self);
        make.width.mas_equalTo(kWindowWidth / RTPagesInScreen);
    }];
    NSMutableArray<UIButton *> *buttonArray = [NSMutableArray arrayWithCapacity:self.nameArray.count];
    for (NSInteger i = 0; i < self.nameArray.count; i ++) {
        UIButton *button = [[UIButton alloc] init];
        [self.scrollView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.scrollView);
            make.bottom.equalTo(self.scrollView);
            make.width.mas_equalTo(kWindowWidth / RTPagesInScreen);
            if (self.nameArray.count < RTPagesInScreen) {
                make.centerX.equalTo(self.scrollView.mas_left).offset((i+1)*kWindowWidth/(self.nameArray.count + 1));
            } else {
                make.left.equalTo(self.scrollView).offset(i * kWindowWidth / RTPagesInScreen);
            }
        }];
        button.tag = i + TYZIndicateViewButtonTags;
        button.titleLabel.font = [UIFont systemFontOfSize:[self getLeastFontSize:15]];
        [button addTarget:self action:@selector(didClickButtons:) forControlEvents:UIControlEventTouchUpInside];
        [buttonArray addObject:button];
    }
    self.buttonArray = [buttonArray copy];
}
// 获取最小字体
- (CGFloat)getLeastFontSize:(CGFloat)fontSize {
    CGFloat font = fontSize;
    NSString *text = [self.nameArray.firstObject stringByAppendingString:@"5555"];
    CGSize size = [text getSizeWithFont:[UIFont systemFontOfSize:font] maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
    if (size.width > kWindowWidth / RTPagesInScreen) {
        for (NSInteger i = 0; i < MAXFLOAT; i ++) {
            CGFloat width = [text getSizeWithFont:[UIFont systemFontOfSize:font] maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)].width;
            if (width > kWindowWidth / RTPagesInScreen) {
                font = font - 0.1;
            } else {
                break;
            }
        }
    }
    return font;
}
// 传递触摸事件
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if ([view isEqual:self]){
        for (UIView *subview in self.scrollView.subviews){
            CGPoint offset = CGPointMake(point.x - self.scrollView.frame.origin.x + self.scrollView.contentOffset.x
                                         - subview.frame.origin.x, point.y - self.scrollView.frame.origin.y
                                         + self.scrollView.contentOffset.y - subview.frame.origin.y);
            
            if ((view = [subview hitTest:offset withEvent:event])){
                return view;
            }
        }
        return self.scrollView;
    }
    return view;
}
// 点击事件
- (void)didClickButtons:(UIButton *)button {
    self.pointX = (button.tag - TYZIndicateViewButtonTags) * kWindowWidth / RTPagesInScreen;
    if (self.didClickIndicateViewItemBlock) {
        self.didClickIndicateViewItemBlock((button.tag - TYZIndicateViewButtonTags) * kWindowWidth);
    }
}
// 设置文字颜色
- (void)changeLabelProperty:(CGFloat)pointX {
    
    [self.buttonArray enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj setTitle:self.nameArray[idx] forState:UIControlStateNormal];
        // 添加一个图标
        __block UIImageView *iconView = [self.scrollView viewWithTag:TYZIndicateViewImageTags + idx];
        if (iconView == nil) {
            iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:TYZIndicateViewImageName]];
            iconView.tag = TYZIndicateViewImageTags + idx;
        }
        if (pointX / kWindowWidth * RTPagesInScreen == idx) {
            TYZLog(@"%zd",idx);
            [obj setTitleColor:IndicateColor forState:UIControlStateNormal];
            obj.titleLabel.font = [UIFont systemFontOfSize:[self getLeastFontSize:15] + 2 weight:0.6];
            [obj addSubview:iconView];
            [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(obj);
                make.bottom.equalTo(obj).offset(5);
                make.width.mas_equalTo(kWindowWidth / RTPagesInScreen * 0.5);
                make.height.mas_equalTo(kWindowWidth / RTPagesInScreen * 0.2);
            }];
            // 自绘图标
            dispatch_async(dispatch_get_main_queue(), ^{
//                [self drawIndicateImage:obj];
            });
        } else {
            [obj setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            obj.titleLabel.font = [UIFont systemFontOfSize:[self getLeastFontSize:15]];
            if (iconView) {
                [iconView removeFromSuperview];
            }
        }
    }];

}
- (void)drawIndicateImage:(UIView *)superView {
    /**
     * 准备基本数据
     */
    CGFloat height = 10;// 三角图标的高
    CGFloat width = 30;// 三角图标的宽
    CGFloat topPointX = superView.center.x;
    CGFloat topPointY = superView.bounds.size.width - height;
    CGFloat leftPointX = superView.center.x - width * 0.5;
    CGFloat leftPointY = superView.bounds.size.width;
    CGFloat rightPointX = superView.center.x + width * 0.5;
    CGFloat rightPointY = superView.bounds.size.width;
    /**
     * 开始绘图
     */
    // 获得当前图形上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 设置起始点为最顶点
    CGContextMoveToPoint(context, topPointX, topPointY);
    // 往左下方绘制第一条线段
    CGContextAddLineToPoint(context, leftPointX, leftPointY);
    // 往右方绘制第二条线段
    CGContextAddLineToPoint(context, rightPointX, rightPointY);
    // 闭合
    CGContextAddLineToPoint(context, topPointX, topPointY);
    // 设置颜色
    [[UIColor whiteColor] set];
    // 实心渲染
    CGContextFillPath(context);
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 控制它在最后显示不出现空白
    if (scrollView.contentOffset.x > kWindowWidth / RTPagesInScreen * (self.nameArray.count - RTPagesInScreen)) {
        [scrollView setContentOffset:
         CGPointMake((self.nameArray.count - RTPagesInScreen) * kWindowWidth / RTPagesInScreen, 0)];
    }
}
#pragma mark - getter & setter
- (void)setButtonArray:(NSArray<UIButton *> *)buttonArray {
    _buttonArray = buttonArray;
    [self changeLabelProperty:0];
}
- (void)setPointX:(CGFloat)pointX {
    _pointX = pointX;
    // 设置偏移量
    if (pointX >= kWindowWidth / RTPagesInScreen * (self.nameArray.count - (RTPagesInScreen - 1) * 0.5)) {
        // 最后面数据无法居中的情况
        [self.scrollView setContentOffset:
         CGPointMake(pointX - kWindowWidth / RTPagesInScreen * (RTPagesInScreen - 1) * 0.5, 0)];
    } else if (pointX >= kWindowWidth / 2) {// 中间数据可以居中的情况
        [self.scrollView setContentOffset:
         CGPointMake(pointX - kWindowWidth / RTPagesInScreen * (RTPagesInScreen - 1) * 0.5, 0)];
    } else {// 最前面数据无法居中的情况
        [self.scrollView setContentOffset:CGPointMake(0, 0)];
    }
    [self changeLabelProperty:pointX];
}
- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.contentSize = CGSizeMake(kWindowWidth / RTPagesInScreen * self.nameArray.count, self.height);
        _scrollView.bounces = NO;
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}
@end
